package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.excpsms.service.INotifyDevelopersService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 *  短信通知开发者异常信息的队列消费者
 * @createDate 2020-11-16
 */
@Component
public class ExcptionSmsConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(ExcptionSmsConsumer.class);

    @Autowired
    INotifyDevelopersService notifyDevelopersService;



    /**
     * <desc>
     *     短信通知开发者异常信息消费端
     * </desc>
     * @param message
     * @param channel
     * @throws InterruptedException
     * @throws IOException
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_NOTIFY_DEVLOPS_EXCPTMSG_QUEUE)
    public void process(Message message, Channel channel) throws  Exception {
        try {
            byte[] body = message.getBody();
            JSONObject  json  = JSON.parseObject(new String(body));
            JSONObject  messageContentJson  =  JSON.parseObject(json.getString("messageContent"));
            String  msg  = messageContentJson.getJSONObject("data").getString("msg");
            notifyDevelopersService.notify( msg);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_短信通知开发者异常信息消费端】:解析异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }




}
